const fs = require('fs');
const path = require('path');

class Logger {
  constructor() {
    this.logLevel = process.env.LOG_LEVEL || 'info';
    this.logFile = process.env.LOG_FILE || './logs/app.log';
    
    // 确保日志目录存在
    const logDir = path.dirname(this.logFile);
    if (!fs.existsSync(logDir)) {
      fs.mkdirSync(logDir, { recursive: true });
    }
    
    this.levels = {
      error: 0,
      warn: 1,
      info: 2,
      debug: 3
    };
  }

  log(level, message, meta = {}) {
    if (this.levels[level] <= this.levels[this.logLevel]) {
      const timestamp = new Date().toISOString();
      const logEntry = {
        timestamp,
        level: level.toUpperCase(),
        message,
        ...meta
      };

      // 控制台输出
      const colorMap = {
        error: '\x1b[31m', // 红色
        warn: '\x1b[33m',  // 黄色
        info: '\x1b[32m',  // 绿色
        debug: '\x1b[36m'  // 青色
      };
      
      const resetColor = '\x1b[0m';
      const color = colorMap[level] || '';
      
      console.log(
        `${color}[${timestamp}] ${level.toUpperCase()}: ${message}${resetColor}`,
        Object.keys(meta).length > 0 ? meta : ''
      );

      // 文件输出
      try {
        fs.appendFileSync(this.logFile, JSON.stringify(logEntry) + '\n');
      } catch (error) {
        console.error('写入日志文件失败:', error);
      }
    }
  }

  error(message, meta = {}) {
    this.log('error', message, meta);
  }

  warn(message, meta = {}) {
    this.log('warn', message, meta);
  }

  info(message, meta = {}) {
    this.log('info', message, meta);
  }

  debug(message, meta = {}) {
    this.log('debug', message, meta);
  }
}

module.exports = new Logger();